import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_baselib/flutter_baselib.dart';
import 'package:flutter_baselib_example/common/config/res_config_impl.dart';
import 'package:flutter_baselib_example/common/config/toast_impl.dart';
import 'package:flutter_baselib_example/common/net/config/http_config_impl.dart';
import 'package:flutter_baselib_example/common/util/ui_utils.dart';
import 'package:flutter_baselib_example/module/login/view/login_view.dart';
import 'package:flutter_baselib_example/module/other/event_demo.dart';
import 'package:flutter_baselib_example/module/other/tools_page.dart';
import 'package:flutter_baselib_example/module/home/view_model/home_view_model.dart';

///@date:  2021/3/1 15:20
///@author:  lixu
///@description:首页
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    _initBaseLib();
  }

  ///初始化基础库
  void _initBaseLib() async {
    await BaseLibPlugin.init(
      isDebug: true,
      //全局通用资源配置
      resConfig: ResConfigImpl(),
      //toast相关配置
      toastImpl: ToastImpl(),
      //bugly相关配置
      buglyConfig: BuglyConfig.defaultAndroid('8b841196c7'),
      //日志库配置
      logConfig: LogConfig.obtain(
        tag: "lixu",
        isConsolePrintLog: true,
        isFlutterPrintLog: false,
        //保存到外部路径时，需要获取存储权限
        saveLogFilePath: '/storage/emulated/0/flutter_xlog_app/baselib_xlog/',
        encryptPubKey: null,
      ),
      //http配置
      httpConfig: HttpConfigImpl(),
    );

    String appInfo = '应用名称：${await PackageUtils.getAppName()}\n'
        '应用包名：${await PackageUtils.getPackageName()}\n'
        '版本号：${await PackageUtils.getVersionName()}\n'
        'SHA1：${await PackageUtils.getBuildSignature()}\n'
        '版本code：${await PackageUtils.getBuildNumber()}\n';

    String deviceInfo = '手机品牌：${await DeviceUtils.getBrand()}\n'
        '手机型号：${await DeviceUtils.getModel()}\n'
        '系统：${DeviceUtils.getOsType()}\n'
        '系统版本：${await DeviceUtils.getOsVersion()}\n';

    LogUtils.i('appInfo', appInfo);
    LogUtils.i('deviceInfo', deviceInfo);

    print('设备详细信息:' + json.encode((await DeviceUtils.getAndroidDeviceInfo())?.toMap()));
    LogUtils.i('getExternalStorageDir:', (await PathUtils.getExternalStorageDir())?.path);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BaseLib 首页'),
      ),
      body: ChangeNotifierProvider(
        create: (_) {
          return HomeViewModel();
        },
        builder: (context, child) {
          return _getChild(context);
        },
      ),
    );
  }

  Widget _getChild(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          UIUtils.getButton('登录页\n（演示：Http的封装）', () {
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return LoginView();
            }));
          }),
          UIUtils.getButton('用户列表页1\n（演示：Http和完整的MVVM实现）\n 进入页面时调用1个接口成功后，才显示UI', () async {
            context.read<HomeViewModel>().toUserListPage(context);
          }),
          UIUtils.getButton('用户列表页2\n（演示：Http和完整的MVVM实现）\n 进入页面时调用2(多)个接口成功后，才显示UI', () async {
            context.read<HomeViewModel>().toUserListPage2(context);
          }),
          UIUtils.getButton('下拉刷新和分页加载功能演示', () {
            context.read<HomeViewModel>().toListLoadPage(context);
          }),
          UIUtils.getButton('EventBus工具演示', () {
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return EventDemo();
            }));
          }),
          UIUtils.getButton('工具类页', () {
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return ToolsPage();
            }));
          }),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    BaseLibPlugin.dispose();
  }
}
